//
//  SYOauthViewController.swift
//  SingWeibo
//
//  Created by shiying on 15/12/18.
//  Copyright © 2015年 shiying. All rights reserved.
//

import UIKit
import SVProgressHUD

class SYOauthViewController: UIViewController ,UIWebViewDelegate {

    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    /// 授权界面开始时显现
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载中...", maskType: SVProgressHUDMaskType.Black)
    }
    
    /// 授权界面结束后
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //MARK: - 设置WebView
        let url = SYAFNTool.sharedInsetace.oAuthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
        //MARK: - 设置导航栏
        setupNavigations()
    }
    
    /// 设置导航栏
    func setupNavigations() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    //MARK: - webView代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let url = request.URL!.absoluteString
        

        if !url.hasPrefix(SYAFNTool.sharedInsetace.redirect_uri) {
            // 返回true去加载
            return true
        }
        
        /*
        当我们授权同意,获取过AccessToken之后,在登录不会弹出授权界面,如果还想弹出来需要先取消授权,取消授权需要到微博界面去
        */
        
        // 是授权回调地址,判断是取消还是授权
        // 获取url中?后面的内容: URL.query就是问号后面的东西
        if let query = request.URL?.query {
            // 能到这里面来,表示query有值
            let codeString = "code="
            // 判断query是否以code=开头
            
            if query.hasPrefix(codeString) {
                // 截取code的值
                // Stirng和NSString之间的转换是不需要添加as? 或 as! 直接使用as
                let queryNS = query as NSString
                let code = queryNS.substringFromIndex(codeString.characters.count)
//                print("code = \(code)")
                
                // 调用当前类的loadAccessToken，下面的方法，传值回到Tool
                loadAccessToken(code)
            } else {
                self.close()
            }
            
        } else {
            print("query没有值")
        }
        
        return false
    }

    
    
    /// 控制器加载AccessToken
    func loadAccessToken(code: String) {
        SYAFNTool.sharedInsetace.loadAccessToken(code) { (result, error) -> () in
            // 如果有错误，那么就提醒用户  如果需要模拟失败，只要判断的时候取反值就可以了 ==nil
            if error != nil && result == nil {
                
                SVProgressHUD.showInfoWithStatus("您的网络不给力", maskType: SVProgressHUDMaskType.Black)
                
                // 延时2秒再关闭
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
                return
            }
//            print("result\(result)")//如果能到下面来，就表示获得AccessToken
            /// 字典转模型
            let userAccount = SYUseAccount(dict: result!)
            /// 保存对象到沙盒
            userAccount.saveUserAccount()
            
            (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootViewController(false)
            
            self.close()
        }
    }
    
    /// 填充
    func fill() {
        let js = "document.getElementById('userId').value='auqfyffyxtdm@sina.com'; document.getElementById('passwd').value='130205xxz';"
        
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
        
    /// 关闭
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }

    //MARK: -懒加载
    private lazy var webView = UIWebView()

}

